var app = getApp();
Page({
    data:{
        siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
        allsort : [],
        alltopic : [],
        citylist : [],
        currentCharNum:0,
        locationState : 0,
        address:false,
        lat : 0,
        lng : 0,
        isshowsort : false,
        sortid : 0,
        content : '',
        pic : [],
        showmal : true,
        starttopic : 0,
        endtopic : 9,
        istop : false,
        total : 0,
        isauth : true,
        ispubing:false,
        tel : '',
        cityid : 0,
        cityname : '',
        isshowcity : false,
        payname : '微信支付',
        paytype : 1,
        paylist : [
            {text:'现金支付'},
            {text:'余额支付'},
            {text:'积分支付'},
        ],
        isshowpay : false,
        toptime : 0,
        allshop : [],
        isshowshop : false,
        shopid : '',
        vedio : {},
    },
    onLoad:function(options){
        var self = this;
        
        app.com.getLocation(self,function(loc){
            var postdata = {
                op:'pubstart',
                lat : loc.latitude,
                lng : loc.longitude,
                issort : 1,
            };
            app.com.http('cityinfo','POST',postdata,0,false,'','',function(res){
                if (!res.data.errno && res.data) {
                    self.setData({
                        params : res.data.data.params,
                        allsort : res.data.data.allsort,
                        alltopic : res.data.data.alltopic,
                        lat : loc.latitude,
                        lng : loc.longitude,
                        citylist : res.data.data.citylist ? res.data.data.citylist : [],
                        paylist : res.data.data.paylist,
                        paytype : res.data.data.paylist[0] ? res.data.data.paylist[0].id : 1,
                        payname : res.data.data.paylist[0] ? res.data.data.paylist[0].text : '',
                        isauth : res.data.data.isauth == 1 ? true : false,
                        allshop : res.data.data.allshop ? res.data.data.allshop : [],
                        inited : true,
                        currentCharNum : 0,
                    },function(){
                        self.countTotal();
                    })
                    self.geocoder(loc.latitude,loc.longitude,res.data.data.params.tenkey);
                    wx.setNavigationBarTitle({
                        title: res.data.data.params.title ? res.data.data.params.title : '发布'
                    });
                }else{
                    app.com.alert(res.data.message,function(){
                        app.com.backPage(0);
                    });
                }
            });
        });
    },
    onPullDownRefresh: function () {
        if( this.data.isdown ) return false;
        this.data.isdown = true;
        this.onLoad();
        this.data.isdown = false;
        this.setData({
            content : '',
            tel : '',
        })
        wx.stopPullDownRefresh();
    },
    onTextInput: function(e) {
        this.setData({
            content : e.detail.value,
            currentCharNum: e.detail.value.length
        });
    },
    addimg(e){
        var self = this;
        var num = self.data.pic.length >= 12 ? 12 : 12-self.data.pic.length;
        wx.chooseImage({
            count: num, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success (res) {

                if( !self.data.pic || self.data.pic.length <= 0 ){
                    self.data.pic = [];
                }
                for(var t in res.tempFilePaths){
                    (function(m){

                        if( self.data.pic.length >= 12 ){
                            app.com.toast('最多12张图片','none');
                            return false;
                        }
                        self.uptomaster(res.tempFilePaths[m],function(resa){

                            if( self.data.pic.length >= 12 ){
                                app.com.toast('最多12张图片','none');
                                return false;
                            }
                            var temp = {id:m,att:resa.attachment,show:resa.url};
                            self.setData({
                                'pic' : self.data.pic.concat(temp)
                            });
                        });

                    })(t)
                }
            }
        })
    },
    onRemoveImgTap: function(e) {
        var index = e.currentTarget.dataset.index;
        this.data.pic.splice(index,1)
        this.setData({
            pic: this.data.pic
        });
    },
    uptomaster(tempurl,fn,type){
        wx.showLoading({mask:true,title:'上传中'});

        var url = app.siteInfo.siteroot+'?i='+app.siteInfo.uniacid+'&j=&c=utility&a=file&do=upload&type=image&thumb=0';
        if(type == 'vedio'){
            var url = app.com.murl('myinit',{op:'upvedio'});
        }  
        wx.uploadFile({
            url: url,
            filePath: tempurl,
            name: 'file',
            success: function(res){
                var aaa = JSON.parse( res.data );
                if(aaa.attachment){
                    if( fn ) fn( aaa );
                }else{
                    app.com.alert('上传失败'+aaa.res);
                }
            },
            complete : function(){
                wx.hideLoading();
            },
            fail(rs){
                console.log(rs)
            }
        })
    },
    addvedio(e){
        var self = this;
        wx.chooseVideo({
            count: 1,
            sourceType: ['album', 'camera'],
            compressed : true,
            maxDuration : 60,
            success (res) {
                self.uptomaster(res.tempFilePath,function(resa){
                    self.setData({
                        'vedio.vedio' : resa.attachment
                    });
                    if(res.thumbTempFilePath){
                        self.uptomaster(res.thumbTempFilePath,function(resa){
                            self.setData({
                                'vedio.thumb' : resa.attachment,
                                'vedio.showthumb' : resa.url,
                            });
                        });
                    }else{
                        self.setData({
                            'vedio.showthumb' : 'http://ddcdn.jd.com/ddimg/jfs/t1/119827/2/9319/4423/5ef2c78eEd49f62e6/3c78f309dbb06dd3.png',
                        });
                    }
                    
                },'vedio');
            }
        })
    },
    onRemovevedio(){
        this.setData({
            'vedio.thumb' : '',
            'vedio.showthumb' : '',
            'vedio.vedio' : '',
        });
    },
    onChangetop(e){
        this.setData({ istop: e.detail });
        this.countTotal();
    },
    geocoder(lat,lng,key){
        var self = this;
        var QQMapWX = require('../resource/js/qqmap-wx-jssdk.min.js');
        var qqmapsdk = new QQMapWX({
            key: key // 必填
        });
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: lat,
                longitude: lng
            },
            success: function(res) {
                self.setData({
                    locationState : 1,
                    address : res.result.address,
                });
            }
        })
    },
    countTotal(){
        var pub = this.data.params.pubprice*1;
        var top = this.data.istop ? this.data.params.topprice*1 : 0;

        if(this.data.paytype == 2){
            pub = this.data.params.pubjf*1;
            top = this.data.istop ? this.data.params.topjf*1 : 0;
        }
        if(this.data.paytype == 3){
            pub = this.data.params.pubum*1;
            top = this.data.istop ? this.data.params.topum*1 : 0;
        }

        var num = 1;
        if(this.data.toptime > 0 ){
            num = this.data.toptime/this.data.params.toptime;
        }

        this.setData({
            total : (pub+top*num).toFixed(2),
        })
    },
    showsort(){
        var self = this;
        if( wx.requestSubscribeMessage ){
            wx.requestSubscribeMessage({
                tmplIds : self.data.params.submess,
                complete : function(){}
            })
        }
        this.setData({
            isshowsort : !this.data.isshowsort
        })
    },
    confirmsort(e){
        this.setData({
            sortname : this.data.allsort[e.detail.index].name,
            sortid : this.data.allsort[e.detail.index].id,
            isshowsort : false,
        })
    },
    showshop(){
        this.setData({
            isshowshop : !this.data.isshowshop
        })
    },
    confirmshop(e){
        this.setData({
            shopname : this.data.allshop[e.detail.index].name,
            shopid : this.data.allshop[e.detail.index].id,
            isshowshop : false,
        })
    },
    showcity(){
        var self = this;
        this.setData({
            isshowcity : !this.data.isshowcity
        })
    },
    confirmcity(e){
        this.setData({
            cityname : this.data.citylist[e.detail.index].text,
            cityid : this.data.citylist[e.detail.index].value,
            isshowcity : false,
        })
    },
    showpay(){
        var self = this;
        this.setData({
            isshowpay : !this.data.isshowpay
        })
    },
    confirmpay(e){
        this.setData({
            payname : this.data.paylist[e.detail.index].text,
            paytype : this.data.paylist[e.detail.index].id,
            isshowpay : false,
        })
        this.countTotal();
    },
    settopic(e){
        var index = e.currentTarget.dataset.index;
        var isact = this.data.alltopic[index].isact == 1 ? 0 : 1;
        if(isact == 1){
            var num = 0;
            for (var i = 0; i < this.data.alltopic.length; i++) {
                if(this.data.alltopic[i].isact == 1) num++;
            }
            if(num >= 3){
                app.com.toast('最多选择3个话题','none');
                return false;
            }
        }

        this.setData({
            ['alltopic['+index+'].isact'] : isact,
        })
    },
    getphone(e){
        var self = this;
        if( e.detail.errMsg == 'getPhoneNumber:ok') {
            var postdata = {
                iv: e.detail.iv,
                encryptedData: e.detail.encryptedData,
                op : 'encrypt'
            };
            app.com.http('user_v1','POST',postdata,0,true,'','',function(res){
                if (!res.data.errno) {
                    self.setData({
                        tel : res.data.data,
                    });
                }
            });
        }else{
            app.com.alert('请允许授权');
        }
    },
    telfn(e){
        this.setData({
            tel : e.detail
        })
    },
    loadTopic(){
        var self = this;
        for (var i = 0; i < this.data.alltopic.length; i++) {
            if(this.data.alltopic[i].isact == 1) {
                this.setData({
                    ['alltopic['+i+'].isact'] : 0,
                })
            }
        }
        this.setData({
            showmal : false,
        })
        var start = 0,end = 0;
        if( this.data.starttopic + 10 >= this.data.alltopic.length > 0 ){
            start = 0;
            end = 9;
        }else{
            start = this.data.starttopic + 10;
            end = this.data.endtopic + 10;
        }
        this.setData({
            starttopic : start,
            endtopic : end,
            showmal : true,
        })
    },
    pub(){
        var self = this;
        if( self.data.isauth ){
            this.loginauth = this.selectComponent('#loginauth');
            this.loginauth.hideauth();
            return false;
        }

        app.com.confirm('发布后不可修改，确定提交发布吗？',function(){

            if(self.data.ispubing) return false;
            self.data.ispubing = true;

            var postdata = {
                op : 'pub',
                content : self.data.content,
                pic : JSON.stringify(self.data.pic),
                address : self.data.address,
                topic : [],
                istop : self.data.istop ? 1 : 0,
                sortid : self.data.sortid,
                cityid : self.data.cityid,
                tel : self.data.tel,
                paytype : self.data.paytype,
                lat : self.data.lat,
                lng : self.data.lng,
                toptime : self.data.toptime,
                shopid : self.data.shopid,
                vedio : self.data.vedio && self.data.vedio.vedio ? self.data.vedio.vedio : '',
                vediothumb : self.data.vedio && self.data.vedio.thumb ? self.data.vedio.thumb : '',
            };

            for (var i = 0; i < self.data.alltopic.length; i++) {
                if(self.data.alltopic[i].isact == 1) {
                    postdata.topic.push(self.data.alltopic[i].id);
                }
            }

            app.com.http('cityinfo','POST',postdata,0,true,'','',function(res){
                self.data.ispubing = false;
                if (!res.data.errno && res.data) {
                    if(res.data.data.ispay == 1){
                        wx.requestPayment({
                            appId : res.data.data.appId,
                            timeStamp: res.data.data.timeStamp,
                            nonceStr: res.data.data.nonceStr,
                            package: res.data.data.package,
                            signType: 'MD5',
                            paySign: res.data.data.paySign,
                            success: function (payres) {
                                if( payres.errMsg == 'requestPayment:ok' ){
                                    self.sucfn(res);
                                }
                            },
                            fail: function (payres) {}
                        });
                    }else{
                        self.sucfn(res);
                    }
                }else if(res.data.errno == 2){
                    app.com.confirm(res.data.message,function(){
                        var tourl = '/zofui_sales/ucard/buycard';
                        wx.navigateTo({
                          url: tourl
                        });
                    },false,'取消','购买会员');
                }else{
                    app.com.alert(res.data.message);
                }
            });

        })
    },
    sucfn(res){
        var self = this;
        app.com.alert(res.data.message ? res.data.message : res.data.data.mess,function(){
            if( res.data.data.url ){
                wx.navigateTo({
                    url : res.data.data.url
                })
            }else{
                wx.navigateBack();
            }
        });
        self.setData({
            content : '',
            pic : [],
        })
    },
    onChangetime(e){
        this.data.toptime = e.detail;
        this.countTotal();
    },
    location : function( e ){
        app.com.location( e );
    },
    otherapp : function( e ){
        app.com.otherapp( e );
    },
    navigateto : function( e ){
        app.com.navigateto( e );
    },
    redirectto : function( e ){
        app.com.redirectto( e );
    },    
    callphone : function(e){
        app.com.callphone( e );
    },
    toweburl : function(e){
        app.com.toweburl( e );
    },
    showimages : function( e ){
        app.com.showimages( e );
    },
    footNavigate(e){
        var url = e.currentTarget.dataset.url;
        wx.switchTab({
          url: url
        })
    },
    authed(){
        this.setData({
            isauth : false,
        })
        this.pub();
    }
})